// pages/detail/detail.js
import jobList from '../../api/detail'
const app = getApp()

Page({
  data: {
    job: {},
    jobList: [],
    id: '',
    isClick: false,
    jobStorage: [],
    jobId: ''
  },

  onLoad: function(options) {
    this.getJobDetail(options.id)
    this.checkCollectionStatus(options.id)
    this.getSimilarJobs()
  },

  getJobDetail: function(id) {
    wx.cloud.callFunction({
      name: 'db',
      data: {
        action: 'getJobDetail',
        jobId: id
      }
    }).then(res => {
      if (res.result.success) {
        this.setData({
          job: res.result.data
        })
      } else {
        wx.showToast({
          title: '获取职位详情失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      console.error('获取职位详情失败:', err)
      wx.showToast({
        title: '获取职位详情失败',
        icon: 'none'
      })
    })
  },

  checkCollectionStatus: function(jobId) {
    wx.cloud.callFunction({
      name: 'db',
      data: {
        action: 'checkCollectionStatus',
        jobId: jobId
      }
    }).then(res => {
      if (res.result.success) {
        this.setData({
          isClick: res.result.isCollected
        })
      }
    }).catch(err => {
      console.error('检查收藏状态失败:', err)
    })
  },

  async getSimilarJobs() {
    try {
      const result = await wx.cloud.callFunction({
        name: 'db',
        data: {
          action: 'getSimilarJobs'
        }
      })
      if (result.result.success) {
        this.setData({
          jobList: result.result.data
        })
      }
    } catch (error) {
      console.error('获取相似职位失败:', error)
    }
  },

  deliver: async function() {
    try {
      // 检查是否有简历
      const resumeResult = await wx.cloud.callFunction({
        name: 'db',
        data: {
          action: 'getUserResume'
        }
      })

      if (!resumeResult.result || !resumeResult.result.resumeUrl) {
        wx.showModal({
          title: '提示',
          content: '请先上传简历',
          confirmText: '去上传',
          success: (res) => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/resume/resume'
              })
            }
          }
        })
        return
      }

      // 创建投递记录
      const result = await wx.cloud.callFunction({
        name: 'db',
        data: {
          action: 'createDeliveryRecord',
          data: {
            jobId: this.data.job._id,
            jobName: this.data.job.jobName,
            companyName: this.data.job.companyName,
            salary: this.data.job.salary,
            location: this.data.job.address
          },
        }
      })

      if (result.result && result.result.success) {
        wx.showToast({
          title: '投递成功'
        })
      } else {
        throw new Error('投递失败')
      }
    } catch (error) {
      console.error('投递失败:', error)
      wx.showToast({
        title: '投递失败',
        icon: 'none'
      })
    }
  },

  click(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../detail/detail?id=${id}`,
    })
  },

  showMore(e) {
    let key = this.data.job.jobName
    wx.navigateTo({
      url: `../search/search?inputValue=${key}`,
    })
  },

  showMap(e) {
    let address = this.data.job.address;
    switch (address) {
      case '杭州':
        this.setData({
          id: '0',
        })
        break;
      case '深圳':
        this.setData({
          id: '1',
        })
        break;
      case '北京':
        this.setData({
          id: '3'
        })
    }
    wx.navigateTo({
      url: `../map/map?id=${this.data.id}`,
    })
  },

  haveSave: function() {
    const job = this.data.job
    wx.cloud.callFunction({
      name: 'db',
      data: {
        action: 'toggleCollection',
        data: {
          jobId: job._id,
          jobName: job.jobName,
          companyName: job.companyName,
          salary: job.salary,
          location: job.address
        }
      }
    }).then(res => {
      if (res.result.success) {
        this.setData({
          isClick: res.result.isCollected
        })
        wx.showToast({
          title: res.result.isCollected ? '收藏成功' : '已取消收藏',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      console.error('收藏操作失败:', err)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    })
  }
})